/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */

package opensocial.apps.common.config;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.configuration.CompositeConfiguration;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.HierarchicalConfiguration;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.configuration.tree.ConfigurationNode;
import org.apache.log4j.Logger;

/**
 * This class manages the configurations for an App. Each App will have a
 * corresponding ConfigFactory instance. The configurations is read only.
 * <p>
 * Each App can have following configurations: <br>
 * 1. An App configuration file. It lists supported containers, the filename for
 * the default configuration, and the filename for the configuration of each
 * container. By default this file is loaded from config/{appId}.xml, you can
 * change this by system property opensocial.apps.{appId}.configFile.<br>
 * 2. A default configuration file.<br>
 * 3. A configuration file for each container.<br>
 * 
 * <p>
 * Sample App Configuration file.
 * 
 * <pre>
 * &lt;opensocial&gt;
 *             &lt;containers&gt;
 *                 &lt;default&gt;
 * 
 *                 &lt;/default&gt;
 *                 &lt;xiaonei&gt;
 *                     &lt;running&gt;true&lt;/running&gt;
 *                     &lt;url&gt;www.xiaonei.com&lt;/url&gt;
 *                     &lt;description&gt;&lt;/description&gt;
 *                 &lt;/xiaonei&gt;
 *                 &lt;51&gt;
 *                     &lt;running&gt;false&lt;/running&gt;
 *                     &lt;url&gt;www.51.com&lt;/url&gt;
 *                     &lt;description&gt;&lt;/description&gt;
 *                 &lt;/51&gt;
 *             &lt;/containers&gt;
 *             &lt;catalogs&gt;
 *                 &lt;default&gt;
 * 
 *                 &lt;/default&gt;
 *                 &lt;xiaonei&gt;
 *                 &lt;/xiaonei&gt;
 *                 &lt;51&gt;
 *                 &lt;/51&gt;
 *             &lt;/catalog&gt;
 * &lt;/opensocial&gt;
 * </pre>
 * 
 * @author guibinkong
 */
public class ConfigFactory {
  private static final Logger LOGGER = Logger.getLogger(ConfigFactory.class);

  private static final String CONFIG_FILE_PROPERTY_PREFIX = "opensocial.";
  private static final String CONFIG_FILE_PROPERTY_NAME = ".configFile";
  private static final String CONFIG_FILE_PROPERTY_NAME_DEFAULT = "config";
  private static final String CONFIG_FILE_PROPERTY_NAME_DEFAULT_PREFIX = "config/";
  private static final String CONFIG_FILE_PROPERTY_NAME_DEFAULT_SUFFIX = ".xml";

  protected static ConfigFactory _instance;

  // whether the App has been loaded successfully?
  private boolean initalized = false;
  // a list for all the containers that this app is running on.
  private List<String> runningContainers = new ArrayList<String>();
  // holds the base description info for each containers.
  private Map<String, Configuration> containerMetas = new HashMap<String, Configuration>();;
  // holds the default app configuration for all containers.
  private Configuration defaultConfiguration;
  // a map to get Configuration by container Id.
  private Map<String, Configuration> configurations = new HashMap<String, Configuration>();

  /**
   * Gets the ConfigFactory instance for an app.
   * 
   * @return its corresponds ConfigFactory. Load configurations from file system
   *         if called first time for this app.
   */
  public static synchronized ConfigFactory getConfigFactory() {
    if (_instance == null) {
      try {
        _instance = new ConfigFactory();
      } catch (ConfigurationException e) {
        LOGGER.error("Failed to load configuration", e);
      }
    }

    return _instance;
  }

  // check if a string is valid for a container id
  public static boolean isValidContainerId(String appId) {
    return (appId != null) && (appId.trim().length() > 0)
        && (appId.indexOf(".") < 0) && (appId.indexOf(" ") < 0);
  }

  @SuppressWarnings( { "unchecked" })
  private ConfigFactory() throws ConfigurationException {
    // loading app configuration......
    String filename = CONFIG_FILE_PROPERTY_NAME_DEFAULT_PREFIX
        + CONFIG_FILE_PROPERTY_NAME_DEFAULT
        + CONFIG_FILE_PROPERTY_NAME_DEFAULT_SUFFIX;

    Configuration appConfig = new XMLConfiguration(filename);
    LOGGER.info("Containers configuration '" + filename + "' loaded.");

    // parsing containers info......
    Configuration containersConfiguration = appConfig.subset("containers");

    HierarchicalConfiguration hc = (HierarchicalConfiguration) containersConfiguration;
    List nodes = hc.getRootNode().getChildren();
    for (Object obj : nodes) {
      String container = ((ConfigurationNode) obj).getName();

      if (!isValidContainerId(container)) {
        String msg = "Failed to initilize app" + ". Container id '" + container
            + "': it cannot be empty, and cannot contains space and '.:'.";
        LOGGER.error(msg);
        throw new ConfigurationException(msg);
      }
      if (containersConfiguration.getBoolean(container + ".running")) {
        runningContainers.add(container);
        containerMetas
            .put(container, containersConfiguration.subset(container));
      }
    }
    if (runningContainers.isEmpty()) {
      String msg = "Failed to initilize app. It should be running on at least one container.";
      LOGGER.error(msg);
      throw new ConfigurationException(msg);
    }

    // parsing default configuration......
    defaultConfiguration = appConfig.subset("containers.default");

    // parsing configuration of each container......
    for (String container : runningContainers) {
      CompositeConfiguration config = new CompositeConfiguration();
      config.addConfiguration(appConfig.subset(CONFIG_FILE_PROPERTY_PREFIX
          + container));
      config.addConfiguration(defaultConfiguration);
      configurations.put(container, config);
    }

    // change the state of the App
    initalized = true;
  }

  public boolean isInitalized() {
    return initalized;
  }

  public List<String> listRunningContainers() {
    return Collections.unmodifiableList(runningContainers);
  }

  public boolean isRunning(String container) {
    return runningContainers.contains(container);
  }

  public Configuration getConfiguration(String container) {
    if (configurations == null) {
      return null;
    }
    if (configurations.get(container) == null) {
      return this.defaultConfiguration;
    } else {
      return configurations.get(container);
    }
  }

  public Configuration getContainerMeta(String container) {
    return containerMetas.get(container);
  }
}
